<?php
/**
 * Created by User: wene<china_wangyu@aliyun.com> Date: 2019/4/12 Time: 14:10
 */

namespace think\restful\validate;


use think\restful\Base;
use think\restful\exception\ApiException;

/**
 * Class Authorize API权限自检类
 * @package think\restful\validate
 */
class Authorize extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function execute():void
    {
        // TODO: Implement execute() method.
        if ($this->config['API_AUTHORIZATION']){
            $this->rule();
        }
    }

    /**
     * 验证规则
     */
    public function rule():void
    {
        try{
            !isset($this->param['timestamp']) && ApiException::exception('请求参数错误：timestamp~'.time());

            $serverTime = time();
            $serverRequestTime = $_SERVER['REQUEST_TIME'];
            $requestTime = $this->param['timestamp'];
            $exp = empty($this->config['API_REQUEST_EXP']) ? 60 : $this->config['API_REQUEST_EXP'];
            $requestCount = empty($this->config['API_HOUR_REQUEST_COUNT']) ? 1000 : $this->config['API_HOUR_REQUEST_COUNT'];
            $cookieName = md5(base64_encode(request()->ip()));
            $date = date('YmdH',$serverTime);
            $ipData = cookie($cookieName);

            if ($serverRequestTime - $requestTime > $exp)ApiException::exception('请求超时~');
            if ($serverTime - $requestTime > $exp)ApiException::exception('请求超时~');
            if ($serverTime - $requestTime < 0)ApiException::exception('请求异常~');
            if ($serverRequestTime - $requestTime < 0)ApiException::exception('请求数据异常~');
            if ($ipData['count'] > $requestCount)ApiException::exception('请求太过频繁，请休息一会再来吧~');
            is_null(cookie($cookieName)) && cookie($cookieName,['count'=> 1,'date'=>$date],3600);
            if ($date > $ipData['date'] or $date < $ipData['date'] )cookie($cookieName,['count'=> 1,'date'=>$date],3600);
            $date == $ipData['date'] && cookie($cookieName,['count'=> $ipData['count'] + 1,'date'=>$date]);
        }catch (\Exception $exception){
            ApiException::exception('500 '.$exception->getMessage());
        }
    }
}